package cn.myfirefly.moming.house.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import cn.myfirefly.moming.house.entity.SpfTradePerformance;
import cn.myfirefly.moming.house.model.SpfTradePerformanceFilterDto;
import cn.myfirefly.core.BaseDao;
import cn.myfirefly.core.model.PageResultDto;
import cn.myfirefly.utils.CollectionUtil;
import cn.myfirefly.utils.FilterUtil;

@Repository
public class SpfTradePerformanceDao extends BaseDao<SpfTradePerformance> {
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PageResultDto getList(SpfTradePerformanceFilterDto dto) {
		Session session = sessionFactory.getCurrentSession();
		PageResultDto resultDto = new PageResultDto();
		
		
		StringBuffer countSql = new StringBuffer("select count(r) from SpfTradePerformance r where 1=1 ");
		StringBuffer querySql = new StringBuffer("from SpfTradePerformance r where 1=1 ");
		
		List paramList = new ArrayList();
		FilterUtil.handleFilterSql(dto, "r", countSql, querySql, paramList);
		
		Query query = session.createQuery(countSql.toString());
		FilterUtil.setQueryParams(query, paramList);
		Number number = (Number)query.uniqueResult();
		resultDto.setTotal(number.intValue());
		if (number.intValue() > 0) {
			query = session.createQuery(querySql.toString());
			FilterUtil.setQueryParams(query, paramList);
			List<SpfTradePerformance> list = query
					.setFirstResult((dto.getPageCurrent() - 1) * dto.getPageSize())
					.setMaxResults(dto.getPageSize())
					.list();
			resultDto.setPageCurrent(dto.getPageCurrent());
			resultDto.setList(list);
		}
		return resultDto;
	}
	
	public SpfTradePerformance getByContractId(Integer contractId) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer querySql = new StringBuffer("from SpfTradePerformance r where r.tradeContractId=:tradeContractId ");
		Query query = session.createQuery(querySql.toString());
		query.setInteger("tradeContractId", contractId);
		@SuppressWarnings("unchecked")
		List<SpfTradePerformance> list = query.list();
		if (CollectionUtil.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}
}
